package com.cn.crmsystem.shiro;

import com.cn.crmsystem.pojo.Login;
import com.cn.crmsystem.pojo.Permission;
import com.cn.crmsystem.pojo.Role;
import com.cn.crmsystem.service.systemService.LoginService;
import com.cn.crmsystem.service.systemService.PermissionService;
import com.cn.crmsystem.service.systemService.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;

public class LoginRealm extends AuthorizingRealm {

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private LoginService loginService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //doGetAuthenticationInfo()  认证用户
        Login login = null;
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //根据名字获取用户的信息 通过service获取查询用户名是否存在
        login = loginService.getLogin(usernamePasswordToken.getUsername());
        if (login == null){
            throw new UnknownAccountException("用户不存在");
        }
        System.out.println("doGetAuthenticationInfo username=" + login.getUserName());
        System.out.println("doGetAuthenticationInfo password=" + login.getPassword());
        ByteSource credentialsSalt = ByteSource.Util.bytes(login.getUserName());    // 以用户名为加密盐值
        String realmName = getName();                                              // 当前realm对象的name，调用父类的getName()方法即可
        //底层  比较
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(login, login.getPassword(), credentialsSalt, realmName);
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
        System.out.println("------用户能看到的功能-------");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Object principal = principals.getPrimaryPrincipal();
        Login login = (Login)principal;
        Integer user_id = login.getUser_id();
        Role role = roleService.getRole(user_id);
        info.addRole(role.getRoleId() + "");
        //查询该角色拥有的权限
        List<Permission> list = permissionService.getPermission(role.getRoleId());
        for (Permission permission : list){
            info.addStringPermission(permission.getPermission_name());//添加权限
        }
        System.out.println("AuthorizationInfo principal=" + principal);
        return info;
    }

}
